package com.feihong.newzxclient.service;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.*;
import android.provider.Settings;
import android.text.TextUtils;
import android.widget.Toast;
import android.text.TextUtils;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.feihong.newzxclient.activity.ActivityManager;
import com.feihong.newzxclient.callback.OnResponseCheckListener;
import com.feihong.newzxclient.callback.OnResponseMessageListener;
import com.feihong.newzxclient.callback.OnResponseRegisterListener;
import com.feihong.newzxclient.config.ZXConfig;
import com.feihong.newzxclient.tcp.*;
import com.feihong.newzxclient.util.PromptUtils;
import com.google.protobuf.InvalidProtocolBufferException;
import io.netty.buffer.ByteBuf;
import zaoxun.Msg;

/**
 * MainService
 *
 * @author xiong
 * @version 1.0.0
 */
public class MainService extends Service {

    private static final String TAG = "MainService";

    private static final int MSG_ID = 0x01;
    private static final long REQUEST_INTERVAL = 0;
    private static final long SEND_GPS_INTERVAL = 5000;

    private long mLastSendTime;
    private final LocalBinder mBinder = new LocalBinder();

    private LocationClient mLocationClient = null;
    private double mLatitude;
    private double mLongitude;

    /**
     * 绑定服务时的返回对象
     */
    public class LocalBinder extends Binder {
        /**
         * 获取服务本身
         *
         * @return 当前服务本身
         */
        public MainService getService() {
            return MainService.this;
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_ID) {
                mLocationClient.requestLocation();
                mHandler.removeMessages(MSG_ID);
                mHandler.sendEmptyMessageDelayed(MSG_ID, REQUEST_INTERVAL);
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);

        mLocationClient = new LocationClient(this);
        mLocationClient.setAK("8771b0569c3afa9d7a8786c80f113815");

        mLocationClient.registerLocationListener(new MyLocationListener());
        LocationClientOption clientOption = new LocationClientOption();
        clientOption.setOpenGps(true);
        clientOption.setCoorType("gps");
        clientOption.setPoiNumber(3);
        clientOption.setAddrType("detail");
        clientOption.setServiceName("com.baidu.location.service_v3.3");
        clientOption.setPoiExtraInfo(true);
        clientOption.setPriority(LocationClientOption.GpsFirst);
        clientOption.disableCache(true);
        clientOption.setPoiDistance(1000);
        clientOption.setScanSpan(10000);
        mLocationClient.setLocOption(clientOption);

        mLocationClient.start();
        mHandler.sendEmptyMessageDelayed(MSG_ID, REQUEST_INTERVAL);

        boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER );
        if(!gpsEnabled) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            PromptUtils.showToast("请先打开GPS", Toast.LENGTH_SHORT);
        }

        /*
        LocationManager locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(true);
        criteria.setBearingRequired(true);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        String provider = locationManager.getBestProvider(criteria, true);
        locationManager.requestLocationUpdates(provider,
                REQUEST_INTERVAL, 0, new MyLocationListener());
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                REQUEST_INTERVAL, 0, new MyLocationListener());
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                REQUEST_INTERVAL, 0, new MyLocationListener());
        locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER,
                REQUEST_INTERVAL, 0, new MyLocationListener());*/

    }

    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                return;
            }

            StringBuffer sb = new StringBuffer(256);
            sb.append("Poi time : ");
            sb.append(location.getTime());
            sb.append(" latitude : ");
            sb.append(location.getLatitude());
            sb.append(" lontitude : ");
            sb.append(location.getLongitude());
            /*sb.append(" radius : ");
            sb.append(location.getBearing());*/
            sb.append(" speed: ");
            sb.append(location.getSpeed());
            sb.append(" derect: ");
            sb.append(location.getDerect());
            sb.append(" altitude: ");
            sb.append(location.getAltitude());

            mLatitude = location.getLatitude();
            mLongitude = location.getLongitude();
            

            if ((System.currentTimeMillis() - mLastSendTime) > SEND_GPS_INTERVAL) {
                String latitude = Double.toString(mLatitude);
                String longitude = Double.toString(mLongitude);
                Activity currentActivity = ActivityManager.instance().getCurrentActivity();
                Msg.CommonMessage.Builder builder = Msg.CommonMessage.newBuilder();
                builder.setType(Msg.MessageType.GPS_DATA);
                Msg.GPSData.Builder gps = Msg.GPSData.newBuilder();
                gps.setLatitude(latitude);
                gps.setLongitude(longitude);
                gps.setTime(location.getTime());
                
                //gps.setDirection(Float.toString(location.getDerect()));
                if (!TextUtils.isEmpty(ZXConfig.getDeviceId())) {
                    gps.setDeviceId(ZXConfig.getDeviceId());
                }
                gps.setElevation(Double.toString(location.getAltitude()));
                //gps.setRadius(Float.toString(location.getBearing()));
                gps.setSpeed(Float.toString(location.getSpeed()));
                builder.setGpsData(gps);
                if (!TextUtils.isEmpty(ZXConfig.getDeviceId())) {
            

                    if(currentActivity instanceof OnResponseMessageListener){
                        ((OnResponseMessageListener)currentActivity).responseGPS(gps.build());
                    }
                    mLastSendTime = System.currentTimeMillis();
                }
            }
            //System.out.println(sb.toString());
        }

        @Override
        public void onReceivePoi(BDLocation bdLocation) {

        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return Service.START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
    }

    public double getLatitude() {
        return (int)(mLatitude*1000000)/1000000.0;
    }

    public double getLogitude() {
        return (int)(mLongitude*1000000)/1000000.0;
    }

    private void handleMessage(Msg.CommonMessage msg) {
        Activity currentActivity = ActivityManager.instance().getCurrentActivity();
        System.out.println("msg type:" + msg.getType());
        switch (msg.getType()) {
            case REGISTER_RESPONSE:
                if (currentActivity instanceof OnResponseRegisterListener) {
                    ((OnResponseRegisterListener)currentActivity).responseRegister(msg.getRegisterResponse());
                }
                break;
            case CHECK_RESPONSE:
                if (currentActivity instanceof OnResponseCheckListener) {
                    ((OnResponseCheckListener)currentActivity).responseCheck(msg.getCheckResponse());
                }
                break;
            case OIL_QUANTITY_RESPONSE:
                if (currentActivity instanceof OnResponseMessageListener) {
                    ((OnResponseMessageListener)currentActivity).responseOilQuantity(msg.getOilQuantityResponse());
                    System.out.println(" deviceId:" + msg.getOilQuantityResponse().getDeviceId() + " oilQuantity:" + msg.getOilQuantityResponse().getQuantity());
                }
                break;
            case SPEED_LIMIT:
                if (currentActivity instanceof OnResponseMessageListener) {
                    ((OnResponseMessageListener)currentActivity).responseSpeedLimit(msg.getSpeedLimit());
                    System.out.println(" deviceId:" + msg.getSpeedLimit().getDeviceId() + " speed:" + msg.getSpeedLimit().getSpeed());
                }
                break;
            case SHORT_MESSAGE:
                if (currentActivity instanceof OnResponseMessageListener) {
                    ((OnResponseMessageListener)currentActivity).responseShortMessage(msg.getShortMessage());
                    System.out.println(" deviceId:" + msg.getShortMessage().getDeviceId() + " short msg :" + msg.getShortMessage().getContent());
                }
                break;
            case GPS_DATA:
                if (currentActivity instanceof OnResponseMessageListener) {
                    ((OnResponseMessageListener)currentActivity).responseGPS(msg.getGpsData());
                }
                break;
            case AUDIO_FILE_DATA:
                if (currentActivity instanceof OnResponseMessageListener) {
                    ((OnResponseMessageListener)currentActivity).responseAudioFile(msg.getAudioFileData());
                    System.out.println(" deviceId:" + msg.getAudioFileData().getDeviceId() + " file:" + msg.getAudioFileData().getFileName());
                }
                break;
            case PRODUCTION_RESPONSE:
                if (currentActivity instanceof OnResponseMessageListener) {
                    System.out.println(" deviceId:" + msg.getProductionResponse().getDeviceId() + " duty:" +msg.getProductionResponse().getPeriod()+" producation:" + msg.getProductionResponse().getQuantity());
                    ((OnResponseMessageListener)currentActivity).responseProduction(msg.getProductionResponse());

                }
            default:
                break;
        }
    }
}
